//
//  SCNetRequest.m
//  SCFoundationKit
//
//  Created by Chao Sheng on 2023/10/16.
//

#import "SCNetRequest.h"
#import <YYModel/YYModel.h>

@interface SCNetRequest ()

@property (nonatomic, assign) NSTimeInterval timeout;

@property (nonatomic, copy) NSString *requestURL;

@property (nonatomic, assign) SCNetRequestHttpMethod httpMethod;

@property (nonatomic, strong) NSDictionary *requestParam;

@property (nonatomic, assign) NSInteger successResponseCode;

 
@end

@implementation SCNetRequest

+ (SCNetRequest *)share{
    static SCNetRequest * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SCNetRequest alloc] init];
    });
    
    manager.timeout = 5;
    manager.successResponseCode = 1;
    
    return manager;
}

- (SCNetRequest * _Nonnull (^)(NSTimeInterval))timeoutinterval {
    return ^SCNetRequest * (NSTimeInterval timeout) {
        self.timeout = timeout;
        return self;
    };
}

- (SCNetRequest * _Nonnull (^)(NSString * _Nonnull))url {
    return ^SCNetRequest * (NSString *url) {
        self.requestURL = url;
        return self;
    };
}

- (SCNetRequest * _Nonnull (^)(SCNetRequestHttpMethod))method {
    return ^ SCNetRequest * (SCNetRequestHttpMethod method){
        self.httpMethod = method;
        return self;
    };
}

- (SCNetRequest * _Nonnull (^)(NSDictionary * _Nonnull))param {
    return  ^SCNetRequest * (NSDictionary *param) {
        self.requestParam = param;
        return self;
    };
}

- (SCNetRequest * _Nonnull (^)(NSInteger))successCode {
    return ^SCNetRequest * (NSInteger code) {
        self.successResponseCode = code;
        return self;
    };
}

- (void)startRequestWithResponse:(void (^)(id response, NSError *error))responseBlock {
    
    NSString *url = [self.requestURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval = self.timeout ? self.timeout : 5.0f;
    
    switch (self.httpMethod) {
        case SCNetRequestHttpMethod_GET:{
            
            request.HTTPMethod = @"GET";
            /// 重新拼接url
            NSMutableArray *keyValues = @[].mutableCopy;
            [self.requestParam enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                [keyValues addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
            }];
            NSString *query = [keyValues componentsJoinedByString:@"&"];
            NSString *urlStr = [[request.URL absoluteString] stringByAppendingFormat:request.URL.query ? @"&%@" : @"?%@", query];
            NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
            request.URL = url;
            
        }
            break;
        case SCNetRequestHttpMethod_POST: {
            
            request.HTTPMethod = @"POST";
            //设置请求头
            [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            //请求体
            request.HTTPBody = [[self.requestParam yy_modelToJSONString] dataUsingEncoding:NSUTF8StringEncoding];
        }
            break;
            
        default:
            break;
    }
    
    //发送请求
    __weak typeof(self) weakSelf = self;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if(error) {
            /// 请求错误
            responseBlock(nil, error);
            return;
        }
        
        if(!data) {
            NSError *error = [NSError errorWithDomain:@"返回数据是nil" code:-1000 userInfo:nil];
            responseBlock(nil, error);
            return;
        }
        
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if(responseDic[@"Code"]) { //Code Msg Data 结构的
            
            NSInteger code = [responseDic[@"Code"] intValue];
            
            if (code == weakSelf.successResponseCode) {
                
                responseBlock(responseDic[@"Data"],nil);
                
            } else {
                NSError *error = [NSError errorWithDomain:responseDic[@"Msg"] code:code userInfo:nil];
                /// 请求错误
                responseBlock(nil, error);
            }
            
        } else {
            /// 请求回调
            responseBlock(responseDic,nil);
        }
        
    }];
    [dataTask resume];
    
}

@end
